package Java基础.JUC同步工具;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @Title 淘宝面试题
 * 1、创建一个集合并提那家add size
 * 2、新创建2个线程，一个用来添加元素，一个线程用来监视集合，当集合大小等于5的时候输出打印
 * @Author zhengqiang.tan
 * @Date 2021/3/26 10:07 AM
 */
public class NotifyTest {
    volatile ArrayList list = new ArrayList();
    public void add(Object o) {
        list.add(o);
    }
    public int size() {
        return list.size();
    }
    public static void main(String[] args) {
        NotifyTest notifyTest = new NotifyTest();
        final Object lock = new Object();
        new Thread(() -> {
            synchronized (lock) {
                System.out.println("t2 start");
                if (notifyTest.size() != 5) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2 end");
            }
            lock.notify();
        }, "t2").start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1 start");
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    notifyTest.add(new Object());
                    System.out.println("add " + i);
                    if (notifyTest.size() == 5) {
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t1 end");
            }
        }, "t1").start();


    }
}
